package com.xcx.robot.net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author: 邢晨旭
 * @Date: 2021/8/12 10:58
 * @Description:
 */
public class UDPServer {

    public static void main(String[] args) throws IOException {
        //新建一个socket绑定8888端口
        DatagramSocket server = new DatagramSocket(8888);
        //接收消息
        byte[] recvBuf = new byte[100];
        DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
        server.receive(recvPacket);
        String recvStr = new String(recvPacket.getData(), 0, recvPacket.getLength());
        System.out.println("来自男朋友的呼唤;" + recvStr);

        //发送消息：根据接受的port确定男朋友在哪
        int port = recvPacket.getPort();
        InetAddress addr = recvPacket.getAddress();
        String sendStr = "不想回复你，只想买衣服";
        byte[] sendBuf;
        sendBuf = sendStr.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, port);
        server.send(sendPacket);
        server.close();
    }
}
